package com.bj58.mis.apm.server.statistics.mock.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;

public class MockFilter implements Filter {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest sevRequest, ServletResponse sevResponse, FilterChain chain)
			throws IOException, ServletException {
		/**
		 * if not a http request then send a error to the client
		 */
		if (sevRequest instanceof HttpServletRequest) {
			HttpServletRequest request = (HttpServletRequest) sevRequest;
			HttpServletResponse response = (HttpServletResponse) sevResponse;

			String path = request.getServletPath();

			String jsonPath = "static" + path + ".json";
			URL url = this.getClass().getClassLoader().getResource(jsonPath);
			if(url != null){
				logger.debug("[Filter]返回mock数据, requestpath={}, mockJsonFile={}", path, jsonPath);
				mockRender(response, url);
			}else{
				chain.doFilter(request, response);
			}

		}
	}


	private void mockRender(HttpServletResponse response, URL jsonUrl) throws IOException {
		response.setContentType("application/json;charset=UTF-8");
		String json = "{\"code\":0,\"message\":\"响应成功\",\"data\":${data}}";

		try (InputStream is = jsonUrl.openStream()) {
			byte[] buffer = new byte[is.available()];
			is.read(buffer);
			String dataJson = new String(buffer, "UTF-8");
			dataJson = dataJson.replaceAll("\\s+", "");
			json = json.replace("${data}", dataJson);
			response.getOutputStream().write(json.getBytes("UTF-8"));
		}
	}


	@Override
	public void destroy() {
	}

}
